<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Haiwei365 extends AbstractApi
{

    public function sign(array $array, string $secret_key)
    {
        ksort($array);
        $sign = urldecode(http_build_query($array)).'&key=' . $secret_key;
        return strtoupper(md5($sign));
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $data = [
            'app_id'            => $bean->getSupplierNum(),
            'timestamp'         => millisecondTimestamp(),
            'product_id'        => $bean->getGoodsId(),
            'recharge_number'   => $bean->getAccount(),
            'amount'            => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'notify_url'        => $bean->getNotifyUrl(),
            'order_no'          => $bean->getOrderNo(),//订单号
        ];
        $data['sign'] = $this->sign($data, $bean->getSecretKey());
        return $data;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('order_no', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['SUCCESS', 'FAILURE']))->setRechargeSuccess($status == 'SUCCESS');
    }
}
